package com.gu.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Mr.Gu
 * date 2020/9/5 9:49
 * function : 数据类型转换
 **/
public class DataConvertUtils {

    private static final Logger logger = LoggerFactory.getLogger(DataConvertUtils.class);

    /**
     * XML格式字符串转换为Map
     * @param strXML    XML字符串
     * @return  转换后的Map
     */
    public static Map<String, String> xmlToMap(String strXML) {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                /*do nothing*/
                ex.printStackTrace();
            }
            return data;
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            return null;
        }
    }

    /**
     * 将map转为xml字符串
     * @param parm  源数据   如果map中包含map的话转换后的xml就会使标签中嵌套标签
     * @param isAddCDATA    数据是否需要放在[CDATA[]]中
     * @param strbuff   需要StringBuffer对象
     * @return  转换后的xml字符串
     */
    public static String mapToXml(Map<Object, Object> parm, boolean isAddCDATA,StringBuffer strbuff) {
        if (null != parm) {
            Set<Map.Entry<Object, Object>> entries = parm.entrySet();
            for (Map.Entry<Object, Object> entry : entries) {
                strbuff.append("<").append(entry.getKey()).append(">");
                if (entry.getValue() instanceof Map) {
                    mapToXml((Map<Object, Object>) entry.getValue(),true,strbuff);
                }else {
                    if (isAddCDATA) {
                        if ("CreateTime".equals(entry.getKey())) {
                            if (null != entry.getValue()) {
                                strbuff.append(entry.getValue());
                            }
                        }else {
                            strbuff.append("<![CDATA[");
                            if (null != entry.getValue()) {
                                strbuff.append(entry.getValue());
                            }
                            strbuff.append("]]>");
                        }
                    } else {
                        if (null != entry.getValue()) {
                            strbuff.append(entry.getValue());
                        }
                    }
                }
                strbuff.append("</").append(entry.getKey()).append(">");
            }
        }
        return strbuff.toString();
    }
}
